﻿/*
   Copyright 2013 Dmitry Bratus

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Flower.Logging;

namespace Flower.Security
{
    /// <summary>
    /// Overrides authorization in the current thread until disposed.
    /// </summary>
    public sealed class AuthorizationOverride : IDisposable
    {
        private static readonly Log Log = LogManager.CreateLog(typeof(AuthorizationOverride).Name);

        [ThreadStatic]
        private static string[] _roles;

        internal static string[] Roles { get { return _roles; } }

        /// <summary>
        /// Overrides authorization in the current thread.
        /// </summary>
        /// <param name="roles">The roles to be returned for all users by the AuthorizationProvider.</param>
        public AuthorizationOverride(params string[] roles)
        {
            _roles = roles;

            Log.Trace(() => string.Format("Authorization overriden with roles: {0}.", string.Join(", ", _roles)));
        }

        public void Dispose()
        {
            _roles = null;
        }
    }
}
